package app.keter.portal.security;

import app.keter.portal.security.core.UserDetailsImpl;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 处理当前用户
 * Created by gulx@neusoft.com on 2020/1/13.
 */
public class CurrentUser {
    private static ThreadLocal<UserDetailsImpl> currentUser = new ThreadLocal<>();

    /**
     * 由AuthenticationTokenFilter每次请求后注入当前用户
     * 同时也可便于单体测试注入当前用户
     * @param userDetails
     */
    public static void setCurrentUser(UserDetailsImpl userDetails) {
        currentUser.set(userDetails);
    }

    public static UserDetailsImpl getCurrentUser() {
        if(currentUser.get()!=null){
            return currentUser.get();
        }
        if(SecurityContextHolder.getContext().getAuthentication()!=null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return (UserDetailsImpl) principal;
        }
        return null;
    }
}
